package com.bjsxt.servlet;

import com.bjsxt.pojo.Book;
import com.bjsxt.service.BookService;
import com.bjsxt.service.impl.BookServiceImpl;
import com.google.gson.GsonBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.util.List;

@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {

     private BookService  bookService=new BookServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");



        String method = req.getParameter("method");

        if("findAll".equals(method)){
            findAll(req,resp);
        }else if("save".equals(method)){
            save(req,resp);
        }


    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //接受前台页面中数据
        String bname = req.getParameter("bname");
        double bprice = Double.parseDouble(req.getParameter("bprice"));
        //sql中date只有年月日  util中Date才含有时分秒
        Date dtdate = Date.valueOf(req.getParameter("dtdate"));
        String prod = req.getParameter("prod");
        Book  book=new Book(  bname,  bprice,  dtdate,  prod);
        //数据处理
        int save = bookService.save(book);
        //z做出响应
        resp.getWriter().println(save);

    }

    //查询所有操作
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        List<Book> list = bookService.findAll();

        String json = new GsonBuilder().setDateFormat("yyyy-MM-dd").create().toJson(list);

        resp.getWriter().println(json);
    }
}
